package com.onlineMIS.ORM.DAO.headQ.inventory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.onlineMIS.ORM.DAO.BaseDAO;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrder;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrderDTO;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrderProduct;
import com.onlineMIS.action.headQ.report.HeadQReportFormBean;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.loggerLocal;

@Repository
public class InventoryOrderDAOImpl extends BaseDAO<InventoryOrder> {

    
	@SuppressWarnings("unchecked")
	public List<InventoryOrder> search(DetachedCriteria criteria) {
		List<InventoryOrder> orderList= new ArrayList<InventoryOrder>();
		
	    orderList = getByCritera(criteria,false);

		return orderList;
	}

	public InventoryOrder retrieveOrder(int order_ID) {
        InventoryOrder order =null;

        order = get(order_ID, false);
        
        if (order != null)
            initialize(order);

		return order;
	}
	
	/**
	 * to calculate the statics of the quantity of the products bought before for the customer
	 * @param barcode
	 * @param customerid
	 * @return
	 */
	public int getQuantityBefore(final String barcode,final int client_id){
    	String HQL = "select sum(op.quantity) from InventoryOrderProduct op where op.productBarcode.barcode=? and op.order.cust.id =? and op.order.order_Status = ?";
    	Object[] values = {barcode, client_id, InventoryOrder.STATUS_ACCOUNT_COMPLETE};

    	List<Object> objects = this.executeHQLSelect(HQL, values, null, true);

                Object quantityObj = objects.get(0);
                if (quantityObj == null)
                	return 0;
                else {
                	return ((Long)quantityObj).intValue();
                }

	}
	
	/**
	 * to initialize the order
	 * @param order
	 */
	public void initialize(InventoryOrder order){
		this.getHibernateTemplate().initialize(order.getProduct_Set());
	}

	/**
	 * to copy the inventory order to another one
	 * @param orderInDB
	 * @return
	 */
	public InventoryOrder copy(InventoryOrder orderInDB) {
		evict(orderInDB);
		
		InventoryOrder order = orderInDB;
		
		order.setOrder_ID(0);
		
		Set<InventoryOrderProduct> orderProducts = order.getProduct_Set();
		for (InventoryOrderProduct orderProduct: orderProducts){
			orderProduct.setID(0);
		}
		
		return order;
	}

	/**
	 * 查询时间范围内的客户
	 * @param formBean
	 * @return
	 */
	public List<Integer> getClientIds(HeadQReportFormBean formBean) {
		String sql = "select DISTINCT( s1.cust.id) from InventoryOrder s1 where s1.order_StartTime between ? and ? and order_Status = 3 and order_type = 0 ";
		// 根据条件补充部分
		List<Object> list = new ArrayList<Object>();
		list.add(Common_util.formStartDate(formBean.getStartDate()));
		list.add(Common_util.formEndDate(formBean.getEndDate()));

		List<Integer> clientIds = new ArrayList<Integer>();

		List<Object> values = this.executeHQLSelect(sql.toString(), list.toArray(), null, true);
			if (values.size() != 0) {
				for (Object record : values) {
					clientIds.add(Common_util.getInt(record));
				}
			}
		return clientIds;
	}

	/**
	 * 根据客户ids和productIds查询客户销售信息
	 * @param clientIds
	 * @param productIds
	 * @param formBean
	 * @return
	 */
	public List<InventoryOrderDTO> selectUnitSalesByClientId(List<Integer> clientIds, List<Integer> productIds,
			HeadQReportFormBean formBean) {
		List<InventoryOrderDTO> orderDTOs = new ArrayList<InventoryOrderDTO>();
			String sql = "select s1.cust.id,s1.cust.name, SUM(s2.quantity),SUM(s2.quantity * s2.recCost),SUM(s2.quantity * s2.wholeSalePrice) from InventoryOrder s1 ,InventoryOrderProduct s2  where s1.order_ID = s2.order.order_ID and s1.order_StartTime between ? and ? and s1.order_Status = ?  and s1.order_type = ? ";

			List<Object> list = new ArrayList<Object>();
			list.add(Common_util.formStartDate(formBean.getStartDate()));
			list.add(Common_util.formEndDate(formBean.getEndDate()));
			list.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);
			list.add(InventoryOrder.TYPE_SALES_ORDER_W);

			// 货品product_ids ,客户client_ids
			if (clientIds.size() != 0 || productIds.size() != 0) {
				if (clientIds.size() != 0) {
					String clientId = "and s1.cust.id in(";
					for (int i = 0; i < clientIds.size(); i++) {
						clientId += clientIds.get(i).toString() + ",";
						if (i == clientIds.size() - 1) {
							clientId += clientIds.get(i) + ")";
						}
					}
					sql += clientId;
				}

				if (productIds.size() != 0) {
					String productId = "and s2.productBarcode.id in(";
					for (int i = 0; i < productIds.size(); i++) {
						productId += productIds.get(i).toString() + ",";
						if (i == productIds.size() - 1) {
							productId += productIds.get(i) + ")";
						}
					}
					sql += productId;
				}
				sql += " group by s1.cust.id";
					List<Object> values = this.executeHQLSelect(sql.toString(), list.toArray(), null, true);

					if (values.size() != 0) {
						for (Object record : values) {
							InventoryOrderDTO dto = new InventoryOrderDTO();
							Object[] records = (Object[]) record;
							dto.setClientId(Common_util.getInt(records[0]));
							dto.setClientName(records[1].toString());
							dto.setTotalQuantity(Common_util.getInt(records[2]));
							dto.setTotalRetailPrice(Common_util.getDouble(records[3]));
							dto.setTotalWholePrice(Common_util.getDouble(records[4]));

							orderDTOs.add(dto);
						}
					}
			}		

		return orderDTOs;
	}

	/**
	 * 根据客户id和货品条件，查询该客户单位销售统计的销售单据明细（批发销售单&&批发退货单）
	 * @param formBean
	 * @param clientId
	 * @param productIds
	 * @return
	 */
	public String selectOrderIds(HeadQReportFormBean formBean, Integer clientId, List<Integer> productIds) {
		String sql = "select DISTINCT(s1.order_ID) from InventoryOrder s1 ,InventoryOrderProduct s2  where s1.order_ID = s2.order.order_ID and s1.order_StartTime between ? and ? and s1.order_Status = ?  and (s1.order_type = ? or s1.order_type = ? )  and s1.cust.id = ?";
		String orderIds = "";
		List<Object> list = new ArrayList<Object>();
		list.add(Common_util.formStartDate(formBean.getStartDate()));
		list.add(Common_util.formEndDate(formBean.getEndDate()));
		list.add(InventoryOrder.STATUS_ACCOUNT_COMPLETE);
		list.add(InventoryOrder.TYPE_SALES_ORDER_W);
		list.add(InventoryOrder.TYPE_SALES_RETURN_ORDER_W);
		list.add(clientId);

		if (productIds.size() != 0) {
			String productId = "and s2.productBarcode.id in(";
			for (int i = 0; i < productIds.size(); i++) {
				if (i == productIds.size() - 1) {
					productId += productIds.get(i) + ")";
				} else {
					productId += productIds.get(i).toString() + ",";
				}
			}
			sql += productId;
		}

		List<Object> values = this.executeHQLSelect(sql.toString(), list.toArray(), null, true);

		if (values.size() != 0) {
				for (Object record : values) {
					orderIds += record + ",";
				}
		}
		return orderIds;
	}

	/**
	 * 根据客户id查询客户退换货品销售金额和数量
	 * 
	 * @param formBean
	 * @param clientId
	 * @return
	 */
	public InventoryOrderDTO selectReturnOrder(HeadQReportFormBean formBean, int clientId,
			List<Integer> productIdsThree) {
		String sql = "select SUM(s2.quantity),SUM(s2.quantity * s2.recCost),SUM(s2.quantity * s2.wholeSalePrice)  from InventoryOrder s1, InventoryOrderProduct s2 where s1.order_ID = s2.order.order_ID and s1.cust.id = ? and s1.order_StartTime between ? and ? and  s1.order_Status = 3  and s1.order_type = ?";
		// 根据条件补充部分
		InventoryOrderDTO dto = new InventoryOrderDTO();
		List<Object> list = new ArrayList<Object>();
		list.add(clientId);
		list.add(Common_util.formStartDate(formBean.getStartDate()));
		list.add(Common_util.formEndDate(formBean.getEndDate()));
		list.add(InventoryOrder.TYPE_SALES_RETURN_ORDER_W);
		if (productIdsThree.size() != 0) {
			sql += " and  s2.productBarcode.id in (";
			for (int i = 0; i < productIdsThree.size(); i++) {
				if (i == productIdsThree.size() - 1) {
					sql +=productIdsThree.get(i).toString() + ")";
				} else {
					sql += productIdsThree.get(i).toString() + ",";
				}
			}

		}
			List<Object> values = this.executeHQLSelect(sql.toString(), list.toArray(), null, true);

			if (values.size() != 0) {
				for (Object record : values) {
					Object[] records = (Object[]) record;
					dto.setTotalQuantity(Common_util.getInt(records[0]));
					dto.setTotalWholePrice(Common_util.getDouble(records[1]));
					dto.setTotalRetailPrice(Common_util.getDouble(records[2]));
				}
			} else {
				dto.setTotalQuantity(0);
				dto.setTotalWholePrice(0.0);
				dto.setTotalRetailPrice(0.0);
			}
		return dto;
	}

		public static String  getMaiduanS(InventoryOrder i) {
		if (i.getIsMaiduan() == 1)
			return "买断";
		else 
			return "";
	}
	
	public static String  getDaimaiS(InventoryOrder i) {
		if (i.getIsDaimai() == 1)
			return "代卖";
		else 
			return "";
	}
	public static String  getTransferS(InventoryOrder i) {
		if (i.getIsTransfer() == 1)
			return "调货";
		else 
			return "";
	}

}
